import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

export interface RequestConfig extends AxiosRequestConfig {
  loading?: boolean;
  token?: string;
}

export class Request {
  private instance: AxiosInstance;
  private baseConfig: RequestConfig = {
    baseURL: '',
    timeout: 5000,
    headers: {
      'Content-Type': 'application/json'
    }
  };

  constructor(config: RequestConfig) {
    this.instance = axios.create({
      ...this.baseConfig,
      ...config
    });

    this.setupInterceptors();
  }

  private setupInterceptors() {
    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const requestConfig = config as RequestConfig;
        // 优先使用传入的 token
        if (requestConfig.token) {
          config.headers.Authorization = `Bearer ${requestConfig.token}`;
        } else {
          // 从 localStorage 获取 userToken
          const userToken = localStorage.getItem('userToken');
          if (userToken) {
            config.headers.Authorization = `Bearer ${userToken}`;
          }
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        return response.data;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }

  public async get<T>(url: string, config?: RequestConfig): Promise<T> {
    return this.instance.get(url, config);
  }

  public async post<T>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    return this.instance.post(url, data, config);
  }

  public async put<T>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    return this.instance.put(url, data, config);
  }

  public async delete<T>(url: string, config?: RequestConfig): Promise<T> {
    return this.instance.delete(url, config);
  }
} 